# coding:utf-8
from odoo import models, fields, api
import dateutil.parser


class OLSaleOrderLineExtend(models.Model):
    _inherit = 'sale.order.line'

    @api.model
    def _get_reason(self):
        for line in self:
            reasons = line.order_id.approve_reason_ids
            arr = []
            for reason in reasons:
                arr.append(reason.name)
            if len(arr) > 0:
                line.reason_str = ','.join(arr)

    @api.model
    def _get_order_date(self):
        for line in self:
            line.date_order = dateutil.parser.parse(line.datetime_order).date()

    datetime_order = fields.Datetime(string='Order Date', related='order_id.date_order')
    reason_str = fields.Char(string='Approve Reason', compute=_get_reason, readonly=True)
    date_order = fields.Date(string='Order Date', compute=_get_order_date, readonly=True)
    incoterm = fields.Many2one('stock.incoterms', string='Incoterms', related='order_id.incoterm')

    @api.multi
    def action_query_history(self):
        self.ensure_one()
        ir_model_data = self.env['ir.model.data']
        try:
            compose_form_id = ir_model_data.get_object_reference('sales_order_history_extend', 'sale_order_history')[1]
        except ValueError:
            compose_form_id = False
        ctx = dict()
        ctx.update({
            'default_model': 'sale.order.line',
            'sale_order_line_ids': self.ids[0]
        })
        return {
            'type': 'ir.actions.act_window',
            'view_type': 'tree',
            'view_mode': 'tree',
            'res_model': 'sale.order.line',
            'views': [(compose_form_id, 'tree')],
            'view_id': compose_form_id,
            'target': 'new',
            'context': ctx,
            'domain': [
                ('product_id', '=', self.product_id.id),
                ('order_partner_id', '=', self.order_partner_id.id),
                ('state', 'in', ('sale', 'done'))
            ]
        }
